package mn.slide.labmed.adapter;

import mn.slide.labmed.HomeTabGroupActivity;
import mn.slide.labmed.R;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ArrayAdapter;

public class WebViewAdapter extends ArrayAdapter<String>
{
	private final Activity	context;
	private final String[]	names;

	public WebViewAdapter( Activity context , String[] names )
	{
		super(context , R.layout.webviewrow , names);
		this.context = context;
		this.names = names;
	}

	static class ViewHolderWeb
	{
		public WebView	textView;
	}

	private class LabMedDetailWebViewClient extends WebViewClient
	{
		public boolean shouldOverrideUrlLoading( WebView view , String url )
		{
			if (url.contains("untersuchung="))
			{
				String modelid = url.split("=")[1].trim();
				HomeTabGroupActivity.group.goSearchMerkAndVerluaf(modelid);
			}
			else if (url.contains("file"))
			{
				String googleDoc = "http://docs.google.com/gview?embedded=true&url=";
				String pdf = "http://labmed.de/de/" + url;
				String pdfUrl = googleDoc + pdf;
				Uri uri = Uri.parse(pdfUrl);
				Intent intent = new Intent(Intent.ACTION_VIEW, uri);
				context.startActivity(intent);
			}
			else
			{
				String pdf = "http://labmed.de/de/" + url;
				Intent intent = new Intent(Intent.ACTION_VIEW);
				intent.setData(Uri.parse(pdf));
				context.startActivity(intent);
			}
			return true;
		}
	}

	@Override
	public View getView( final int position , View convertView , ViewGroup parent )
	{
		ViewHolderWeb holder;
		View rowView = convertView;
		if (rowView == null)
		{
			LayoutInflater inflater = context.getLayoutInflater();
			rowView = inflater.inflate(R.layout.webviewrow, null, true);
			holder = new ViewHolderWeb();
			notifyDataSetChanged();
			holder.textView = (WebView) rowView.findViewById(R.id.webView1);
			holder.textView.setWebViewClient(new LabMedDetailWebViewClient());
			rowView.setTag(holder);
		}
		else
		{
			holder = (ViewHolderWeb) rowView.getTag();
		}
		holder.textView.loadData(names[position], "text/html", "UTF-8");
		return rowView;
	}

}